package vn.bang.xiangqi.server;

import java.io.IOException;
import java.net.DatagramSocket;
import java.util.Collection;
import java.util.Map;
import java.util.Queue;

import vn.bang.communication.Command;
import vn.bang.communication.Command.CommandName;
import vn.bang.communication.Communicator;
import vn.bang.entity.GameDTO;
import vn.bang.entity.PlayerDTO;
import vn.bang.utility.SocketUtil;
import vn.bang.xiangqi.server.business.PlayerBusiness;
import vn.bang.xiangqi.server.log.Log;


public class LoginServer extends AbstractBaseServer {
	
	public LoginServer(Queue<Command> commandQueue, Map<Long, Communicator> communicators, Collection<PlayerDTO> players, Collection<GameDTO> games, int numberOfThreads) {
		super(commandQueue, communicators, players, games, numberOfThreads);
	}
	
	@Override
	protected void start() {
		listenLogin();
	}

	@Override
	protected void stop() {
		saveAllPlayers();
	}

	private void saveAllPlayers() {
		PlayerBusiness.saveAll(players);
	}

	private void listenLogin() {
		try {
			int minPort = ServerPort.LOGIN.getValue();
			int maxPort = minPort + super.getNumberOfThreads() - 1;
			final DatagramSocket loginSocket = SocketUtil.getDatagramSocket(minPort, maxPort);
			if (null != loginSocket) {
				Communicator communicator = new Communicator(loginSocket);
				Command command = communicator.listenCommand();
				if (isLoginCommand(command)) {
					addCommandToQueue(command);
				}
			}
			
		} catch (IOException ioException) {
			Log.error("If an I/O error occurs.", ioException);
		}
	}

	private boolean isLoginCommand(Command command) {
		return command.isName(CommandName.LOGIN);
	}
	
}
